const commentMixin = {
	computed: {
		pageSize () {
			return this.$store.getters['app/getPageSize']
		}
	},
	data () {
		return {
			commentShow: false,
			comments: [],
			commentLoading: false,
			commentLoadmore: false,
			commentCurrentPage: 1,
			commentNextUrl: '',
			commentIsLastPage: false,
			commentParams: ''
		}
	},
	methods: {
		async getComment (type) {
			const params = this.commentParams?.commentUrl ? this.commentParams : this.params
			return await this.$store.dispatch('network/request', {
				name: 'comment',
				url: this.commentNextUrl || params.commentUrl,
				source: params.source,
				data: Object.assign({}, params, {
					currentPage: this.commentCurrentPage
				})
			}).then(res => {
				let list, nextUrl, isLastPage
				if ( res.code == this.app.$config.ERR_OK ) {
					const isContained = type == 'loadmore' ? this.app.$utils.isContained(this.comments, res.data.list) : false
					list = isContained ? [] : res.data.list
					nextUrl = res.data.nextUrl
					isLastPage = isContained || res.data.isLastPage
				} else {
					list = []
					nextUrl = ''
					isLastPage = true
				}
				return {
					data: {list, nextUrl, isLastPage}
				}
			})
		},
		handleCommentPulldown (callback) {
			const commentRef = this.app.$utils.typeof(this.$refs.comment) == 'Array' ? this.$refs.comment[0] : this.$refs.comment
			commentRef.resetLoadmore()
			this.commentCurrentPage = 1
			this.commentNextUrl = ''
			this.getComment().then(res => {
				const list = res.data?.list || []
				this.commentLoading = false
				this.comments = list
				this.commentNextUrl = res.data?.nextUrl || ''
				this.commentIsLastPage = typeof res.data?.isLastPage == 'undefined' ? true : res.data?.isLastPage
				if ( this.commentIsLastPage ){ commentRef.setLoadmoreEnd() }
				else if ( list.length > this.pageSize ) { callback ? callback('success') : commentRef.setLoadmoreSuccess() }
				else { this.handleCommentLoadmore(callback) }
			})
		},
		handleCommentLoadmore (callback, length=0) {
			this.commentCurrentPage++
			this.commentLoadmore = true
			this.getComment('loadmore').then(res => {
				this.commentLoadmore = false
				const list = res.data?.list || []
				this.comments = this.comments.concat(list)
				this.commentNextUrl = res.data?.nextUrl || ''
				this.commentIsLastPage = typeof res.data?.isLastPage == 'undefined' ? true : res.data?.isLastPage
				const commentRef = this.app.$utils.typeof(this.$refs.comment) == 'Array' ? this.$refs.comment[0] : this.$refs.comment
				if ( this.commentIsLastPage ){ callback ? callback('end') : commentRef.setLoadmoreEnd() }
				else if ( list.length + length > this.pageSize ) { callback ? callback('success') : commentRef.setLoadmoreSuccess() }
				else {  this.handleCommentLoadmore(callback, list.length + length) }
			})
		}
	}
}

export default commentMixin